package com.lyf.network.learn.bionio;

import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import org.junit.Test;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author LYF
 * @date 2022/6/27
 */
public class BioNioTests {
    /*
    测试：BIO
    BIO: Blocking I O 阻塞IO
     */
    @Test
    public void testBio() throws IOException {
        ServerSocket
                serverSocket = new ServerSocket(8888);
        while (true){
            Socket socket = serverSocket.accept();// 建立连接socket
            System.out.println("connected.."+socket.getRemoteSocketAddress());
            InputStream inputStream = socket.getInputStream();
            //int read = inputStream.read();// 关注 read()方法--一个个字节进行读

            OutputStream outputStream = socket.getOutputStream();
            //OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            //writer.write();

            // 写入HTTP协议响应头,固定写法

            outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
            outputStream.write("Content‐Type:text/html\r\n".getBytes());


//            // 写入HTTP协定响应头,固定写法
//            os.write("HTTP/1.1 200 OK\r\n".getBytes());
//            os.write("Content‐Type:text/html\r\n".getBytes());
            // 必须要写入空行,否则浏览器不解析
            outputStream.write("\r\n".getBytes());

            outputStream.write("hello".getBytes());

            outputStream.flush();
            //writer.flush();
        }
    }

    /*

     */
    @Test
    public void testBIO() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        // 监听连接
        Socket socket = serverSocket.accept();
        System.out.println("connected...::"+socket.getRemoteSocketAddress());

        InputStream is = socket.getInputStream();
        int len = 0;
        byte[] reqData = new byte[1024];
        System.out.println("req data is::");

//        while((len=is.read(reqData))!=-1){
//            System.out.println(new String(reqData,0,len));
//        }

        OutputStream os = socket.getOutputStream();
        ///os.write("".getBytes());
        os.write("HTTP/1.1 200 OK\r\n".getBytes());
        os.write("Content‐Type:text/html\r\n".getBytes());
        os.write("\r\n".getBytes());
        os.write("hello,bio".getBytes());

        //os.close();
        //is.close();
        socket.close();
    }

    HttpResponse buildHttpResp(){
        //  HttpResponse httpResponse = new
        DefaultHttpResponse httpResponse=new DefaultHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK);//new DefaultHttpResponse();
        return (HttpResponse) httpResponse;
    }






}
